package com.neo.push.server.handler;
import com.neo.push.core.SocketRegisterMessage;
import com.neo.push.core.TextMessage;
import com.neo.push.core.connection.ConnectionFactory;
import com.neo.push.core.connection.SocketConnection;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Created by lock on 17-7-11.
 */
public class ServerMessageHandler extends ChannelInboundHandlerAdapter {

    private SocketConnection connection;
    private final ConnectionFactory connectionFactory;
    private Logger logger = LoggerFactory.getLogger(ServerMessageHandler.class);

    public ServerMessageHandler(ConnectionFactory connectionFactory) {
        this.connectionFactory = connectionFactory;
    }




    @Override
    public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
        connection = connectionFactory.instanceConnection(ctx);
    }


    /**
     * 如果收到注册消息，那么将去进行注册，否则处理使用连接进行消息处理
     * @param ctx
     * @param msg
     * @throws Exception
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if(msg instanceof SocketRegisterMessage){
            connection.register(((SocketRegisterMessage)msg).getRegisterMessage());
        }else{
            connection.acceptMessage((TextMessage) msg);
        }

    }



    /**
     * 如果出现异常情况,包括 read idle exception
     *
     * @param ctx
     * @param cause
     * @throws Exception
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        connection.handleThrowable(cause);
    }

    /**
     * 当连接不活动的时候
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        logger.info(" channel :"+ctx.channel().id().asLongText()+" is inactive !");
        connection.close();
    }



}
